package com.example.mvvmtest.viewModel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mvvmtest.Repository.UserRepository
import com.example.mvvmtest.model.entity.User
import kotlinx.coroutines.launch

class RegisterActivityViewModel(override val userRepository: UserRepository): UserViewModel(userRepository) {
    // 表单数据
    private val _id = MutableLiveData("")
    val id: LiveData<String> = _id

    private val _password = MutableLiveData("")
    val password: LiveData<String> = _password

    private val _confirmPassword = MutableLiveData("")
    val confirmPassword: LiveData<String> = _confirmPassword

    // 状态
    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _errorMessage = MutableLiveData("")
    val errorMessage: LiveData<String> = _errorMessage

    private val _registerSuccess = MutableLiveData(false)
    val registerSuccess: LiveData<Boolean> = _registerSuccess

    // 更新输入
    fun onIdChanged(id: String) {
        _id.value = id
        _errorMessage.value = ""
    }

    fun onPasswordChanged(password: String) {
        _password.value = password
        _errorMessage.value = ""
    }

    fun onConfirmPasswordChanged(confirmPassword: String) {
        _confirmPassword.value = confirmPassword
        _errorMessage.value = ""
    }

    // 注册逻辑
    fun register() {
        val id = _id.value?.trim() ?: ""
        val password = _password.value?.trim() ?: ""
        val confirmPwd = _confirmPassword.value?.trim() ?: ""

        // 本地验证
        when {
            id.isEmpty() -> _errorMessage.value = "账号不能为空"
            password.isEmpty() -> _errorMessage.value = "密码不能为空"
            password != confirmPwd -> _errorMessage.value = "两次密码不一致"
            !isPasswordValid(password) -> _errorMessage.value = "密码需≥8位且包含大小写字母和数字"
            else -> {
                // 网络/数据库操作
                viewModelScope.launch {
                    _isLoading.value = true
                    try {
                        if (userRepository.checkIsRegister(id)) {
                            _errorMessage.value = "账号已存在"
                        } else {
                            // 注册新用户（name/job/age用默认值）
                            userRepository.registerUser(User(id = id, password = password))
                            _registerSuccess.value = true
                        }
                    } catch (e: Exception) {
                        _errorMessage.value = "注册失败: ${e.message}"
                    } finally {
                        _isLoading.value = false
                    }
                }
            }
        }
    }

    // 重置注册状态
    fun resetRegisterState() {
        _registerSuccess.value = false
    }
}